<?php

namespace app\admin\model\template;

use app\admin\model\Node;
use app\admin\model\NodeDetail;
use app\admin\model\User;
use think\Model;

/**
 * 模板模型类
 */
class Template extends Model
{

    // 定义关联的数据表名称
    protected $name = 'template';
    // 开启自动时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';


    protected $type = [
        'snapshot' => 'array',
        'images' => 'array',
        'node_detail' => 'array',
        'createtime' => 'timestamp:Y-m-d H:i:s',
        'checktime' => 'timestamp:Y-m-d H:i:s'
    ];

    public function getUpdatetimeAttr($value)
    {
        return date('Y年m月d日', $value);
    }

    public function orderInfo()
    {
        return $this->hasOne(Order::class, 'template_id', 'id');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }


    public function product()
    {
        return $this->hasOne(Product::class, 'id', 'product_id');
    }

    public function getLastReviewInfoAttr()
    {
        return $this->review()->order('createtime', 'desc')->find();
    }

    public function review()
    {
        return $this->hasMany(Review::class, 'template_id', 'id');
    }

    public function getTemplateSn(): string
    {
        $no_use = true;
        $sn = '';
        while ($no_use) {
            $sn = get_random_str(3, 14);
            if (!$this->where('sn', $sn)->find()) {
                $no_use = false;
            }
        }
        return $sn;
    }

    public function getProductSnAttr($value, $data)
    {
        if (isset($data['product_id']) && $data['product_id']) {
            return Product::where('id', $data['product_id'])->value('sn');
        }
        return null;
    }

    public function getTemplateNodeByProductId(int $product_id)
    {
        $nodes = Node::where('product_id', $product_id)
            ->field('id,pid,name as topic,level,path,is_factor,factor_id,node_type,`rank`,from_template,template_mark')
            ->select();
        if ($nodes) {
            $nodes = $nodes->each(function ($item) {
                $item->append(['factor_name']);
            });
        }
        return $nodes;
    }

    public function isTemplateNodeByProductId(int $product_id,$user_id): bool
    {
        return (bool)Node::where('product_id', $product_id)->where('user_id','<>',$user_id)->sum('is_template');
        /* $nodeTemplateId = Node::where('product_id', $product_id)->where('is_template',1)->column('template_id');
        if ($nodeTemplateId) {
            $nodeTemplateId = array_values(array_unique($nodeTemplateId));
            $tUserId =  Template::where('id', 'in', $nodeTemplateId)->column('user_id');
            $tUserId = array_values(array_filter(array_unique($tUserId)));
            if (count($tUserId) > 1) {
                return true;
            } else {
                if (!in_array($user_id,$tUserId)) {
                    return true;
                }
            }
        }
        return false;*/
    }

    public function getCompanyNameAttr($value, $data)
    {

        if (isset($data['user_id'])) {
            if ($data['user_id'] == 0) return '平台';
            return \app\admin\model\User::where('id', $data['user_id'])->value('company_name') ?: '平台';
        }
        return '平台';

    }

    public function getTemplateNodeDetailByProductId(int $product_id)
    {
        return NodeDetail::where('product_id', $product_id)
            ->field('id,node_id,io_type_id,io_category_id,type')
            ->select();
    }

    public function getSalesAttr($value, $data)
    {
        if ($value < 10000) return $value;
        return $value < 100000000 ? substr($value, 0, -4) . '万+' : substr($value, 0, -8) . '亿+';
    }

    public function groupInfo()
    {
        return $this->hasOne(TemplateCategory::class, 'id', 'group_id');
    }

    public function category()
    {
        return $this->hasOne(TemplateCategory::class, 'id', 'category_id');
    }

    public function getGroupNameAttr()
    {
        return $this->groupInfo()->value('name');
    }

    public function getCategoryNameAttr()
    {
        return $this->category()->value('name');
    }

}